package com.example.demo.controller;

import com.example.demo.security.otp.Totp;
import com.example.demo.security.otp.api.Base32;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@Slf4j
public class IndexController {

    protected Map<String, String> userSecret = new ConcurrentHashMap<>();

    /**
     * 提取创建返回Map的逻辑
     *
     * @param label
     * @param secret
     * @return
     */
    private Map<String, Object> createResponseMap(String label, String secret) {
        Totp totp = new Totp(secret);
        Map<String, Object> json = new HashMap<>();
        json.put("user", label);
        json.put("secret", secret);
//        json.put("qrCodeLink", totp.uri(label, "测试站点", "https://profile-avatar.csdnimg.cn/511a50cc8c96418f8317cedbf10ae895_jenrey.jpg"));
        json.put("qrCodeLink", totp.uri(label, "测试站点1"));
        return json;
    }

    /**
     * 生成新的密钥
     *
     * @param username
     * @return
     */
    private String generateNewSecret(String username) {
        return Base32.random();
    }

    @GetMapping("bind/code")
    public Map<String, Object> bindCode(@RequestParam String username) {
        if (username == null || username.trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        String secret = userSecret.computeIfAbsent(username, this::generateNewSecret);
        return createResponseMap(username, secret);
    }

    @GetMapping("/verify/code")
    public Boolean check(@RequestParam String username, @RequestParam String code) {
        if (username == null || username.trim().isEmpty() || code == null || code.trim().isEmpty()) {
            throw new IllegalArgumentException("用户名或验证码不能为空");
        }
        String secret = userSecret.getOrDefault(username, "");
        if (secret.isEmpty()) {
            throw new IllegalArgumentException("用户未绑定");
        }
        Totp totp = new Totp(secret);
        return totp.verify(code);
    }
}
